import 'package:flutter/material.dart';
import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart';

class SecondPage extends StatefulWidget {
  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    // 记录页面开始事件
    UmengAnalyticsPlugin.pageStart("second_page");
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // 记录页面结束事件
    UmengAnalyticsPlugin.pageEnd("second_page");
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      UmengAnalyticsPlugin.event('didChangeShow');
    } else if (state == AppLifecycleState.paused) {
      UmengAnalyticsPlugin.event('didChangeHide');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('第二页'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('这是第二个页面'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                print('返回按钮点击');
                try {
                  // 先记录事件，再执行返回
                  UmengAnalyticsPlugin.event('back_button_clicked');
                  Navigator.pop(context);
                } catch (e) {
                  print('返回失败: $e');
                }
              },
              child: Text('返回首页'),
            ),
          ],
        ),
      ),
    );
  }
}